﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace CRS.Web
{
    public class LogicUserAmountHelper
    {
        private const string SESSION_ID = "SessionId", USER_CODE = "UserCode", LAST_ACTIVE_DATE = "LastActiveDate";

        private static DataTable m_LogicUserInfos;

        public static DataTable LogicUserInfos
        {
            get 
            { 
                if (m_LogicUserInfos == null) 
                    InitLogicUserInfos();
                return m_LogicUserInfos;
            }
        }

        public static void InitLogicUserInfos()
        {
            m_LogicUserInfos = new DataTable();
            m_LogicUserInfos.Columns.Add(SESSION_ID, typeof (string));
            m_LogicUserInfos.Columns.Add(USER_CODE, typeof (string));
            m_LogicUserInfos.Columns.Add(LAST_ACTIVE_DATE, typeof (DateTime));
        }

        public static int GetLogicUserAmount()
        {
            var timeCondition = DateTime.Now.AddSeconds(-60);
            var rs = LogicUserInfos.Select(LAST_ACTIVE_DATE + " >= '"+timeCondition.ToString("yyyy-MM-dd HH:mm:ss")+"'");
            if(LogicUserInfos.Rows.Count - rs.Length > 50)
            {
                lock(m_LogicUserInfos)
                {
                    var rsOld = LogicUserInfos.Select(LAST_ACTIVE_DATE + " < '"+timeCondition.ToString("yyyy-MM-dd HH:mm:ss")+"'");
                    foreach (var r in rsOld)
                        LogicUserInfos.Rows.Remove(r);
                }
            }
            return rs.Length;
        }

        public static void SetLogicUserInfo(string sessionId,string userCode)
        {
            if (String.IsNullOrEmpty(sessionId) || String.IsNullOrEmpty(userCode)) return;
            if (m_LogicUserInfos == null) InitLogicUserInfos();
            lock(m_LogicUserInfos)
            {
                var rs = LogicUserInfos.Select(SESSION_ID + "='"+sessionId+"' and " + USER_CODE + "='"+userCode+"'");
                if(rs.Length==0)
                    LogicUserInfos.Rows.Add(new object[] {sessionId,userCode,DateTime.Now});
                else
                {
                    rs[0][LAST_ACTIVE_DATE] = DateTime.Now;
                }
            }
        }
    }
}
